package com.king.nio.filechannel;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * ByteBuffer 完成文件读取写出
 *
 * @author king
 * @date 2020/12/26 22:53
 */
public class NioFileChannel03 {
    public static void main(String[] args) throws IOException {
        // 获取输入输出管道
        FileInputStream fileInputStream = new FileInputStream("e:/NioFileChannel01.txt");
        FileChannel fileInputStreamChannel = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("e:/NioFileChannel02.txt");
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

        // 获取 byteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        

        while(true){
            // 对 byteBuffer 复位，否则 position 会与 limit 一直，导致一直为0
            byteBuffer.clear();
            int read = fileInputStreamChannel.read(byteBuffer);
            if(-1 == read){
                break;
            }
            // 翻转写出
            byteBuffer.flip();
            fileOutputStreamChannel.write(byteBuffer);
        }
    }
}
